package com.shadow.demo.info.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shadow.demo.data.info.entity.SentenceInfoEntity;
import com.shadow.demo.data.info.mapper.SentenceMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@DS("info")
@Service
public class SentenceService {

    @Resource
    private SentenceMapper sentenceMapper;

    /**
     * 一言
     * */
    public String one() {
        long current = RandomUtils.nextLong(0, count() + 1L);
        log.info("current : {}", current);
        Page<SentenceInfoEntity> page = sentenceMapper.selectPage(
                new Page<>(current, 1L),
                buildWrapper()
        );
        return page.getRecords().stream()
                .map(SentenceInfoEntity::getSentence)
                .findFirst()
                .orElse(null);
    }

    /**
     * 查询总数
     * */
    private Long count() {
        Long count = sentenceMapper.selectCount(buildWrapper());
        if (log.isDebugEnabled()) {
            log.debug("count : {}", count);
        }
        return count;
    }

    /**
     * 构造查询条件
     * 可以用来限定范围
     * */
    private LambdaQueryWrapper<SentenceInfoEntity> buildWrapper() {
        return new LambdaQueryWrapper<SentenceInfoEntity>()
                .apply("LENGTH(sentence) > {0}", 5);
    }
}
